# Direct outputs eligible for public release

# GLOBAL SETTINGS --------------------------------------------------------------

options(
  scipen = 999,
  digits = 16,
  max.print = .Machine$integer.max,
  show.error.locations = TRUE,
  warn = 1
)

RNGkind("L'Ecuyer-CMRG")
seed <- 818675309L
set.seed(seed) # setting main seed

# PACKAGES ---------------------------------------------------------------------

library(data.table)

# PACKAGE SETTINGS -------------------------------------------------------------

# data.table
setDTthreads(threads = 1)
options(datatable.print.class = TRUE, datatable.print.keys = TRUE)
# so that printing the data.table also shows the variable type on top

# BEGIN FILE -------------------------------------------------------------------

# Just in case something masks 'source()', use extra deliberate base::source().
base::source("~/code/0-utility-functions/table-and-text-utils.R", local = TRUE)

# READ IN OUR DATA -------------------------------------------------------------

# Focus on the aggregate (+1 to +5) estimates (event_time == 99) throughout

any_job_to_job_dt <-
    readRDS(
        "~/estimation-output/wealth_effect_estimates_firm_move.rds" #nolint
    )
setnames(any_job_to_job_dt, "ref_event_time", "event_time")
any_job_to_job_dt <- any_job_to_job_dt[event_time == 99]

down_job_to_job_dt <-
    readRDS(
        "~/estimation-output/wealth_effect_estimates_firm_move_down.rds" #nolint
    )
setnames(down_job_to_job_dt, "ref_event_time", "event_time")
down_job_to_job_dt <-
    down_job_to_job_dt[event_time == 99]

up_job_to_job_dt <-
    readRDS(
        "~/estimation-output/wealth_effect_estimates_firm_move_up.rds" #nolint
    )
setnames(up_job_to_job_dt, "ref_event_time", "event_time")
up_job_to_job_dt <-
    up_job_to_job_dt[event_time == 99]

# MAKE TABLE -------------------------------------------------------------------

filedir <- "~/paper/tables/table-A.12.tex"
file.create(filedir)

# Start Table A.12
start_latex_table(
    column_structure = "ccccccc",
    file_dir = filedir,
    append = TRUE
)
add_latex_table_rule(rule_type = "toprule", file_dir = filedir, append = TRUE)
add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)

heading_text_input1 <-
    " &  &  & \\multicolumn{4}{c}{Sample} "
write_latex_table_row(heading_text_input1, file_dir = filedir, append = TRUE)

add_latex_cmidrule(
    point_start_col = "l",
    point_end_col = "r",
    start_col = 4,
    end_col = 7,
    file_dir = filedir,
    append = TRUE
)

heading_text_input2 <-
    " \\multirow{3}{*}{Outcome} & \\multirow{3}{*}{Value} & & \\multirow{2}{*}{Full Sample} & & Quartile 1  &  Quartile 4 " #nolint
write_latex_table_row(heading_text_input2, file_dir = filedir, append = TRUE)

heading_text_input3 <-
    "  & & & & & Pre-Win Income  &  Pre-Win Income "
write_latex_table_row(heading_text_input3, file_dir = filedir, append = TRUE)

heading_text_input4 <-
    "  & & & (1) & & (2)  &  (3) "
write_latex_table_row(heading_text_input4, file_dir = filedir, append = TRUE)

heading_text_input1 <- NULL
heading_text_input2 <- NULL
heading_text_input3 <- NULL
heading_text_input4 <- NULL
rm(
    heading_text_input1,
    heading_text_input2,
    heading_text_input3,
    heading_text_input4
)

add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Add body of Table A.12
# - introduce convenience functions given a similar structure throughout

TableA12Row1 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            "\\multirow{4}{*}{%s} & Estimate & & %s & & %s & %s",
            text,
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

TableA12Row2 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Standard Error & & (%s) & & (%s) & (%s)",
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

TableA12Row3 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Counterfactual Mean & & %s & & %s & %s",
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

TableA12Row4 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Percentage Change & & %s & & %s & %s",
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}


# Any Job-to-Job Move
TableA12Row1(
    dt = any_job_to_job_dt,
    text = "Any Job-to-Job Move",
    scaler = 100000
)
TableA12Row2(
    dt = any_job_to_job_dt,
    scaler = 100000
)
TableA12Row3(
    dt = any_job_to_job_dt,
    scaler = 1
)
TableA12Row4(
    dt = any_job_to_job_dt,
    scaler = 10000000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Downward Move
TableA12Row1(
    dt = down_job_to_job_dt,
    text = "Downward Move",
    scaler = 100000
)
TableA12Row2(
    dt = down_job_to_job_dt,
    scaler = 100000
)
TableA12Row3(
    dt = down_job_to_job_dt,
    scaler = 1
)
TableA12Row4(
    dt = down_job_to_job_dt,
    scaler = 10000000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Upward Move
TableA12Row1(
    dt = up_job_to_job_dt,
    text = "Upward Move",
    scaler = 100000
)
TableA12Row2(
    dt = up_job_to_job_dt,
    scaler = 100000
)
TableA12Row3(
    dt = up_job_to_job_dt,
    scaler = 1
)
TableA12Row4(
    dt = up_job_to_job_dt,
    scaler = 10000000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# End Table A.12
add_latex_table_rule(
  rule_type = "bottomrule",
  file_dir = filedir,
  append = TRUE
)
end_latex_table(file_dir = filedir, append = TRUE)
filedir <- NULL
rm(filedir)

# Housekeeping
any_job_to_job_dt <- NULL
down_job_to_job_dt <- NULL
up_job_to_job_dt <- NULL
rm(any_job_to_job_dt, down_job_to_job_dt, up_job_to_job_dt)